package main

import (
	"context"
	amqp "github.com/rabbitmq/amqp091-go"
	"log"
	"os"
	"strings"
	"time"
)

func main() {
	// 连接 MQ
	conn, err := amqp.Dial("amqp://guest@localhost:5672/")
	failOnError("Failed to connect to RabbitMQ", err)
	defer conn.Close()

	// 创建一个通道操作 MQ
	ch, err := conn.Channel()
	failOnError("Failed to open a channel", err)
	defer ch.Close()

	// 声明一个队列
	q, err := ch.QueueDeclare(
		"task_queue", // RabbitMQ 不允许设置已存在队列 会报错
		true,         // 持久化存储
		false,
		false,
		false,
		nil,
	)
	failOnError("Failed to declare a queue", err)

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 发送消息
	body := bodyFrom(os.Args)
	err = ch.PublishWithContext(ctx,
		"",
		q.Name,
		false,
		false,
		amqp.Publishing{
			DeliveryMode: amqp.Persistent, // 持久化 把消息存到磁盘
			ContentType:  "text/plain",
			Body:         []byte(body),
		})
	failOnError("Failed to publish a message", err)
	log.Printf(" [x] Sent %s\n", body)
}

func failOnError(msg string, err error) {
	if err != nil {
		log.Panicf("%s: %s", msg, err)
	}
}

func bodyFrom(args []string) string {
	var s string
	if len(args) < 2 || os.Args[1] == "" {
		s = "hello"
	} else {
		s = strings.Join(args[1:], " ")
	}
	return s
}
